package com.sms.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @author mis_wu
 * @date 2021/12/11 11:41
 * 短信验证码
 */
@Component
public class SMSUtils {

    private static final Logger log = LoggerFactory.getLogger(SMSUtils.class);

    @Value("${ali.sms.accessKeyId}")
    private String accessKeyId;
    @Value("${ali.sms.secret}")
    private String secret;
    @Value("${ali.sms.singerName}")
    private String singerName; //短信签名
    @Value("${ali.sms.templateCode}")
    private String templateCode;//短息模板
    @Value("${ali.sms.regionId}")
    private String regionId;//短信服务区区域

    public void sendMsg(String phone, String code){
        //连接
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);
        //构建请求
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        //自定义模板信息
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", singerName);//你的阿里云签名的名称
        request.putQueryParameter("TemplateCode", templateCode);
        //request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");
        //构建验证码
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", code);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("阿里云短信响应信息 {}",response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
            throw new RuntimeException("提示:阿里云服务异常!");
        } catch (ClientException e) {
            e.printStackTrace();
            throw new RuntimeException("提示:短信发送失败!");
        }

    }
}
